// axios基础的封装
import axios from "axios";
import {MessageBox, Notification} from "element-ui";
import router from "@/router";

const httpInstance = axios.create({
	baseURL: "http://192.168.1.44:7000",
	timeout: 5000
})
export let baseURL = "http://192.168.1.44:7000";

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
	// 1.从缓存中获取token数据
	let token = sessionStorage.getItem("token");
	if (token) {
		config.headers.token = token;
	}
	return config;
}, e => Promise.reject(e));


// axios响应拦截器
httpInstance.interceptors.response.use(response => {
	const res = response.data;
	if (res.code === 200) {
		return res;
	} else if (res.code === 403) {
		// 身份过期
		MessageBox.confirm("用户登录身份已过期，请重新登录", "系统提示", {
			confirmButtonText: "重新登录",
			cancelButtonText: "取消",
			type: "warning"
		}).then(() => {
			window.localStorage.removeItem('token')
			router.push("/login")
		})

	} else if (res.code === 401) {
		Notification.error({
			title: res.msg
		})
		// return Promise.reject("error")
	} else if (res.code === 508) {
		return res;
	} else if (res.code === 500) {
		Notification.error({
			title: "服务器内部出现异常，请联系管理员处理"
		})
	} else {
		return res
	}
}, e => {
	return Promise.reject(e);
})


export default httpInstance;

